﻿namespace TfsExtensions.Build.Controls
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.VersionControl.Client;
    using Microsoft.TeamFoundation.Server;
    using System.Windows.Forms;

    public partial class DialogBrowseServerFolder : Form
    {
        public VersionControlServer TfsVersionControlServer { get; set; }
        public ICommonStructureService TfsCommonStructureService { get; set; } 
        public string TfsServerName { get; set; }
        public string SelectedPath { get; set; }

        char[] charSeparators = null;
       
        public DialogBrowseServerFolder()
        {
            InitializeComponent();
            txtFolderPath.Text = SelectedPath;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtFolderPath.Text))
            {
                SelectedPath = txtFolderPath.Text;
            }
            else
            {
                SelectedPath = "$/";
            }

            this.DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void GetPathFiles(TreeNode TreeItem, String path, int targetLevel)
        {
            try
            {
                Item[] items = null;

                // Get the latest version of the information for the items.
                ItemSet itemSet = TfsVersionControlServer.GetItems(path, VersionSpec.Latest, RecursionType.OneLevel, DeletedState.NonDeleted, ItemType.Folder);
                items = itemSet.Items;

                foreach (Item keyItem in items)
                {
                    charSeparators = new char[] { '/' };
                    //Using split to isolated the Project Name and the File Name
                    string[] ss = keyItem.ServerItem.Split(charSeparators, StringSplitOptions.None);

                    //!= items[0] ignore the first item, the Team Project Name
                    if (keyItem != items[0] && keyItem.ItemType == ItemType.Folder)
                    {
                        TreeNode new_item = new TreeNode();
                        //Get File or Folder Name
                        string filename = keyItem.ServerItem.Replace(path + "/", string.Empty);
                        new_item.Text = filename;
                        new_item.Tag = keyItem.ServerItem;
                        new_item.ImageIndex = 2;
                        TreeItem.Nodes.Add(new_item);

                        if (new_item.Level < targetLevel)
                        {
                            GetPathFiles(new_item, keyItem.ServerItem, targetLevel);
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private TreeNode SearchTree(TreeNodeCollection nodes, string searchtext)
        {
            TreeNode n_found_node = null;
            bool b_node_found = false;
            foreach (TreeNode node in nodes)
            {
                if (node.Tag.ToString() as string == searchtext)
                {
                    b_node_found = true;
                    n_found_node = node;
                }
                if (!b_node_found)
                {
                    if (n_found_node != null)
                        return n_found_node;
                    else
                    {
                        n_found_node = SearchTree(node.Nodes, searchtext);
                    }
                }
            }

            return n_found_node;
        } 


        private void frmBrowseforFolder_Load(object sender, EventArgs e)
        {
            txtServerPath.Text = TfsServerName;
            TreeNode rootNode = new TreeNode();
            rootNode.Text = TfsServerName;
            rootNode.ImageIndex = 0;
            rootNode.Tag = "$/";

            ProjectInfo[] reveresedProjects = TfsCommonStructureService.ListAllProjects();
            ProjectInfo[] projects = new ProjectInfo[reveresedProjects.Length] ;
            for(int i=reveresedProjects.Length, j=0; i>0; i--, j++)
            {
                projects[j] = reveresedProjects[i-1];
            }
            

            foreach (ProjectInfo project in projects)
            {
                TreeNode childNode = new TreeNode();
                childNode.Text = project.Name;
                childNode.Tag = "$/" + project.Name;
                childNode.ImageIndex = 1;
                GetPathFiles(childNode, "$/" + project.Name,2);
                rootNode.Nodes.Add(childNode);
            }

            treeFolders.Nodes.Add(rootNode);

            //TODO: Ensure logic to highlight selected node
            //if (SelectedPath != "")
            //{
            //    TreeNode foundNode = SearchTree(treeFolders.Nodes, SelectedPath);
            //    treeFolders.SelectedNode = foundNode;
            //    treeFolders.SelectedNode.EnsureVisible();
            //    treeFolders.SelectedNode.BackColor = Color.Yellow;
            //}
        }

        private void treeFolders_AfterSelect(object sender, TreeViewEventArgs e)
        {
            charSeparators = new char[] { '/' };
            string[] ss = e.Node.Tag.ToString().Split(charSeparators, StringSplitOptions.None);
            txtFolderPath.Text = e.Node.Tag.ToString();
       
            if (e.Node.Tag.ToString() == "$/")
            {
                e.Node.ImageIndex = 0;
                e.Node.SelectedImageIndex = 0;
            }
            else if (ss.Length == 2)
            {
                e.Node.ImageIndex = 1;
                e.Node.SelectedImageIndex = 1;
            }
            else if (ss.Length > 2)
            {
                if (e.Node.IsExpanded)
                {
                    e.Node.ImageIndex = 3;
                    e.Node.SelectedImageIndex = 3;
                }
                else
                {
                    e.Node.ImageIndex = 2;
                    e.Node.SelectedImageIndex = 2;
                }
            }
        }

        private void treeFolders_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
        {
            if (e.Node.Parent != null)
            {
                int currentIndex = e.Node.ImageIndex;
                e.Node.ImageIndex = 4;
                e.Node.SelectedImageIndex = 4;
                for (int i = e.Node.Nodes.Count-1; i >= 0; i--)
                {
                    e.Node.Nodes[i].Remove();
                }

                GetPathFiles(e.Node, e.Node.Tag.ToString(), e.Node.Level + 2);
                e.Node.ImageIndex = currentIndex;
                e.Node.SelectedImageIndex = currentIndex;
            }
        }

        private void treeFolders_AfterExpand(object sender, TreeViewEventArgs e)
        {
            charSeparators = new char[] { '/' };
            string[] ss = e.Node.Tag.ToString().Split(charSeparators, StringSplitOptions.None);

            if (ss.Length > 2)
            {
                if (e.Node.IsExpanded)
                {
                    e.Node.ImageIndex = 3;
                    e.Node.SelectedImageIndex = 3;
                }
                else
                {
                    e.Node.ImageIndex = 2;
                    e.Node.SelectedImageIndex = 2;
                }
            }
        }

        private void treeFolders_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            charSeparators = new char[] { '/' };
            string[] ss = e.Node.Tag.ToString().Split(charSeparators, StringSplitOptions.None);
            if (ss.Length > 2)
            {
                if (e.Node.IsExpanded)
                {
                    e.Node.ImageIndex = 3;
                    e.Node.SelectedImageIndex = 3;
                }
                else
                {
                    e.Node.ImageIndex = 2;
                    e.Node.SelectedImageIndex = 2;
                }
            }
        }

        private void treeFolders_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            charSeparators = new char[] { '/' };
            string[] ss = e.Node.Tag.ToString().Split(charSeparators, StringSplitOptions.None);
            if (ss.Length > 2)
            {
                if (e.Node.IsExpanded)
                {
                    e.Node.ImageIndex = 3;
                    e.Node.SelectedImageIndex = 3;
                }
                else
                {
                    e.Node.ImageIndex = 2;
                    e.Node.SelectedImageIndex = 2;
                }
            }
        }
    }
}
